var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var price = 0;
var hot = 0;
var app = getApp();

var screnn_w = 320;

var wxAuthFail = true;
var inviteuid = 0;
var uid = '0';
var linkcode = '';
var topicid = "";
var dataall;
var loadingMore = false;
var allGoodsData = {};
var page = 1;
var hasMore = true;
var messagetmp = '';

Page({
  data: {
    util: util,
    isShow: false,
    page: 1,
    data: [],
    noData: false,
    hasMore: true,
    hasLoadding: false,
    allcata: [],
    nowcata: [],
    content_item_w: 100,
    goodTypeView_w: 100,
    colorSet: '',
    goodsList:[],
    currcata:0,
    catadata:[],
    gwc_count: 0,
    gcataid:"",
    isIphone_x: false,
    nav_bgColor: '#ffffff',
  },
  onLoad: function (options) {
    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
      options:options,
    });

   
    var titlename = tc == 1 ? '積分換購' : '积分换购';
    
    wx.setNavigationBarTitle({
      title: titlename,
    }); 

    wx.showLoading({
      title: tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck"
      },
      success: function (responseData) {
        app.isShow = responseData.data.isShow;
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });

    wx.getSystemInfo({
      success: function (res) {
    
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          screnn_w : res.windowWidth,
          content_w: res.windowWidth - 78,
          goodTypeView_w: (res.windowWidth - 78) / 3
        });
        
      }
    })
    
    //获取颜色配置
    app.getColorSetData(function (color) {
      var col = color.goods_col ? parseInt(color.goods_col) : 3;
      col = col > 0 ? col : 3;
      that.setData({
        colorSet: color,
        content_item_w: (that.data.content_w - (col + 1) * 5) / col,
        goodTypeView_w: screnn_w / 3
      })
      that.resetNavColor();
    });
  

    allGoodsData = {};
    
    var inviteuid = options.inviteuid;
    util.api({
      data: {
        "tc": that.data.tc,
        "publickey": util.publiccode,
        "ac": "goodstype"
      },
      success: function (responseData) {
        console.log("goodstype", responseData.data);
        var goodsType = responseData.data;
        var goodId = options.gcataid;
       
        console.log("goodId", goodId);
        that.setData({
          gcataid: '717',
        });
        if(goodId =="0"){
          if(!goodsType.msg){
            dataall = goodsType;
            console.log("catadata==6==",dataall);
            that.setData({
              catadata: dataall,
              allGoodsDataArray: dataall,
              selectCata: dataall[0],
              gcataid: dataall[0]['goods_id'],
              nowcata: dataall[0].child
            });

           
              that.getAllGoodsData();

           
          } else {
            wx.hideLoading();
          }
        }else{
            var cata = [];
            if(!goodsType.msg){
              for (var i = 0; i < goodsType.length; i++) {
                var gid = goodsType[i].goods_id;
                console.log("===gid===!:"+gid);
                if(goodId == gid){
                  cata = goodsType[i].child == undefined ? goodsType : goodsType[i].child;
                  break;
                }

              } 
              console.log("===cata===!:"+cata);
              if(cata && cata.length >=1 ){
                dataall = cata;
              }else{
                dataall = goodsType;
              }
              console.log("catadata==7==",dataall);
              that.setData({
                catadata: dataall,
                allGoodsDataArray: dataall,
                selectCata: dataall[0],
                nowcata: dataall
              });
              
                that.getAllGoodsData();

             
            } else {
              wx.hideLoading();
            }
        }
        
      }
    });
    that.setData({
      windowWidth: wx.getSystemInfoSync().windowWidth,
      windowHeight: wx.getSystemInfoSync().windowHeight
    });
 

  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },

  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
    return {
      title: '',
      path: '/pages/goodslist/goodslist?&inviteuid=' + inviteuid + '&gcataid=' + that.data.gcataid + '&title=' + that.data.options.title + '&title_f=' + that.data.options.title_f
    };
  },

  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    var that=this;
    that.updateSwiperHeight();
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  pageScrollToBottom: function () {
    var that=this;
    wx.createSelectorQuery().select('#j_page').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: rect.bottom
      });
      that.setData({
        scrollTop: rect.bottom
      })
      console.log("pageScrollToBottom", rect.bottom)
    }).exec()
  },
 
  updateSwiperHeight:function(){
    var that=this;
    var minheight = that.data.windowHeight - 110;
    var heightnow = that.data.goodsList.length * 135
    that.setData({
      swiper_h: heightnow > minheight ? heightnow : minheight
    })
    console.log("swiper_h", that.data.swiper_h)
    
  },

  //载入所有商品
  getAllGoodsData:function(){
    console.log("getAllGoodsData")
    var that=this;
    // var arr=that.data.allGoodsDataArray;
    // for (var i = 0; i < arr.length; i++) {
      var id = that.data.gcataid
      that.loadFenleiGoodsData(id, 1);
      // that.loadFenleiTopicData(id, 1);
    // }
  },

  loadFenleiGoodsData: function (goodsId, index) {
    console.log("loadFenleiGoodsData")
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      toporder: '1',
      tc: that.data.tc,
      orgid: util.orgid,
      gtype: goodsId,
      // zhiding: '1',
      page: 1,
      num: 10
    };
    console.log("商品参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("商品数据" + goodsId + ": ", result);
        if (result.msg) {
            that.setData({
              noData: true
            });
        } else {
          result.forEach(function (n, j) {
            n.message = app.parseHTMLText(n.message);
            var nodes = WxParse.getImgurls('detailMessage', 'html', n.message, that, 12).nodes;
            console.log("nodes:", nodes)

            that.whileNodes(nodes);
            console.log(messagetmp)
            n.message = messagetmp;
            messagetmp = ''
          })
          that.data.allGoodsDataArray.forEach(function (m, i) {
            if (m.goods_id == goodsId) {
              result = that.getGwcData(result)
              m.goodsList = result;

    

            }
          });
        }
        that.setData({
          allGoodsDataArray: that.data.allGoodsDataArray
        })
        console.log("allGoodsDataArray商品数据", that.data.allGoodsDataArray);
        wx.hideLoading();
      }
    });
  }, 
 
  // 购物车商品选择数数据
  getGwcData:function(data){
    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    gwc_datas.forEach(function (m, i) {
      for (var j = 0; j < data.length; j++) {
        var n = data[j];
        if (0 && n.guigelist) {
          for (var k = 0; k < n.guigelist.length; k++) {
            if (m.selGuige.id == n.guigelist[k].id) {
              n.guigelist[k].selectednum = m.buycount;
            }

          }

        } else {
          if (m.id == n.id) {
            n.selectednum = m.buycount;

          }
        }
      }
    })
    return data
  },

  // 滚动列表反应
  scrollAction: function (e) {
    console.log(e)
    console.log("e.detail.source", e.detail.source)

    var that = this;
    var interval = e.timeStamp - that.data.timeStamp;
    interval = Math.abs(interval);
    if (interval < 500) {
      return
    }
    var arr = that.data.allGoodsDataArray;
    var itemBottom = 0;
    var itemTop = 0;
    for (var i = 0; i < arr.length; i++) {
      if (!arr[i].goodsList) {
        arr[i].goodsList = []
      }
      itemTop = itemBottom;
      if(i==0){
        itemBottom = itemBottom+270
      }
      itemBottom = itemBottom + 135 * arr[i].goodsList.length + 25;
      if (e.detail.scrollTop < itemBottom && e.detail.scrollTop > itemTop && that.data.currcata != i) {

        that.setData({
          currcata: i,
          goodsList: arr[i].goodsList,
          timeStamp: e.timeStamp
        })

        return
      }
    }


  },

  whileNodes: function (n) {
    var that = this
    for (let i = 0; i < n.length; i++) {
      if (n[i].node && n[i].node == "text") {
        console.log("text:", n[i].text)
        messagetmp += n[i].text
        return;
      }
      if (n[i].nodes) {
        console.log("whileNodes:", n[i].nodes)
        that.whileNodes(n[i].nodes);
      }
    }

  },
})